package com.kui.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gson.Gson;
import com.kui.entity.Qikan;
import com.kui.entity.Type;
import com.kui.entity.User;
import com.kui.entity.Wenxian;
import com.kui.service.QikanService;
import com.kui.service.TypeService;
import com.kui.service.WenxianService;
import com.kui.util.DateUtil;
import com.kui.util.UUUtil;

public class AddWenxianServlet extends HttpServlet {


	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		
		
		if("member".equals(user.getRole())){
			response.sendRedirect("main.jspx");
			return;
		}
		
		QikanService qs = new QikanService();
		List<Qikan> qikanlist = qs.findAll();
		request.setAttribute("qikanlist", qikanlist);
		request.getRequestDispatcher("WEB-INF/views/addwx.jsp").forward(request, response);
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			String m = request.getParameter("m");
			if("type".equals(m)){
				String value = request.getParameter("value");
				if(value == null || "empty".equals(value) ){
					return;
					
				}else{
					TypeService ts = new TypeService();
					List<Type> typelist = ts.findByQikanId(value);
					response.setContentType("application/json;charset=utf-8");
					Gson gson = new Gson();
					String json = gson.toJson(typelist);
					PrintWriter out = response.getWriter();
					out.print(json);
					out.flush();
					out.close();
					
				}
					
					
			}
			
			if("submit".equals(m)){
				//获取服务器内当前工厂的绝对路径
				String path = getServletContext().getRealPath("/");
				//创建upload文件夹和缓存文件夹
				File file = new File(path + "/upload");
				File temp = new File("d:/temp");
				if(!file.exists()) {
					file.mkdir();
				}
				
				if(!temp.exists()) {
					temp.mkdir();
				}
			
				if(ServletFileUpload.isMultipartContent(request)){
					//设置磁盘文件工厂，缓存大小，缓存文件夹
					DiskFileItemFactory dif = new DiskFileItemFactory();
					dif.setSizeThreshold(4096);
					dif.setRepository(temp);
					
					ServletFileUpload servletFileUpload = new ServletFileUpload(dif);
					//单个文件的上传体积限制
					servletFileUpload.setSizeMax(1024*1024*300);
					
					try {
						@SuppressWarnings("unchecked")
						List<FileItem> list = servletFileUpload.parseRequest(request);
						if(list.size()==0 || list == null){
							response.sendRedirect("addwenxian.jspx");
							return;
						}else{
							Wenxian w = new Wenxian();
							List<String> strlist = new ArrayList<String>();
							for(FileItem item : list){
								if(item.isFormField()){
									//接收不是文件类型的数据
									String qikan = item.getString("UTF-8");
									
									strlist.add(qikan);
									
									
									
								}else{
									
									//判断是不是没有选择文件直接点击上传
									if(item.getName() == ""){
										response.sendRedirect("addwenxian.jspx" );
										return;
									}
									
									String str = "";
									if(item.getName().indexOf(".") > 0){
										 str = item.getName().substring(item.getName().lastIndexOf(".")+1);
										 
									}else {
										 str = "";
									}
									
									
									//给文件重命名，防止在upload文件夹里面的重名
									String randomName = UUUtil.getUUID() +"." +str;
									w.setDownname(randomName);
									w.setSize((int) item.getSize());
									w.setType(str);
									item.write(new File(file,randomName));
								}
								
								
							}
							
							w.setId(strlist.get(0)+"("+strlist.get(1)+")"+strlist.get(2));
							w.setName(strlist.get(4));
							w.setAuthor(strlist.get(5));
							w.setTime(strlist.get(1));
							w.setCreatetime(DateUtil.getNow());
							w.setDesc(strlist.get(6));
							w.setKeyword(strlist.get(7));
							w.setT_type_id(strlist.get(3));
							w.setT_qikan_id(strlist.get(0));
							WenxianService ws = new WenxianService();
							
							ws.save(w);
							
							//上传到upload
							
							response.sendRedirect("wenxiancontrol.jspx");
							
									
						}}
						
					 catch (Exception e) {
						e.printStackTrace();
					}
					
					
					
					
					
					
				}
				
				
				
				
				
				
				
				
				
				
				
				
				
			}
		
	}

}
